<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/axios.js"></script>
</head>
<body>
    <form action="">
        <p>
            用户名:<input type="text" name="uname"><span id="msg"></span>
        </p>
        <p>
            密码:<input type="password" name="upwd">
        </p>
        <p>
            姓名:<input type="text" name="realname">
        </p>
        <p>
            年龄:<input type="number" name="uage">
        </p>
        <p>
            手机号<input type="tel" name="uphone">
        </p>
        <p>
            <button>注册</button>
        </p>
    </form>
    <script>
        axios.defaults.headers.post["Content-Type"]="application/x-www-form-urlencoded";
        axios.defaults.baseURL="http://useker.cn";
        var oForm=document.forms[0];
        var isFlag=false;
        var oMsg=document.querySelector("#msg");

        function debounce(callback,delay=1000){
            var timer;
            return function(){
                let self=this;
                clearTimeout(timer);
                timer=setTimeout(function(){
                    callback.bind(self)();
                },delay)
            }
        }

        // 判断用户是否存在
        oForm.uname.oninput=debounce(function(){
            var strName=this.value;
            axios.get("/checkName",{
                params:{
                    uname:strName
                }
            }).then(function(res){
                console.log(res);
                if(res.data.code==0){
                    isFlag=false;
                    oMsg.innerHTML=res.data.msg.fontcolor("red");
                }else{
                    isFlag=true;
                    oMsg.innerHTML=res.data.msg.fontcolor("green");
                }
            })
        })


        oForm.onsubmit=function(){
            if(isFlag){
                var oUser={
                    uname:oForm.uname.value,
                    upwd:oForm.upwd.value,
                    uage:oForm.uage.value,
                    uphone:oForm.uphone.value,
                    realname:oForm.realname.value
                }
                axios.post("/reg",oUser).then(function(res){
                    console.log(res);
                    alert(res.data.msg);
                    
                })
            }
            return false;
        }
    </script>
</body>
</html>